package com.jams.goodox.db;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


/**
 * @author HP
 */
public class MySQLiteHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "youyang.db";
    private static final int DB_VERSION = 1;

    private static final String KEY_TABLE_ID = "id";

    public static final String TB_COUNTRY_LIST = "down_list";

    public static final String KEY_COUNTRY_LIST_NAME = "name";
    public static final String KEY_COUNTRY_LIST_PIC = "pic";
    public static final String KEY_COUNTRY_LIST_TITLE = "title";
    public static final String KEY_COUNTRY_LIST_URL = "url";


    private SQLiteDatabase mDb;
    private int mDBCount = 0;

    public MySQLiteHelper(Context context) {
        this(context, DB_NAME, null, DB_VERSION);
    }


    public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createCountryListTable(db);
    }

    private void createCountryListTable(SQLiteDatabase db) {
        String sql = "create table " + TB_COUNTRY_LIST
                + " (" + KEY_TABLE_ID + " integer primary key autoincrement, "
                + KEY_COUNTRY_LIST_NAME + " text, "
                + KEY_COUNTRY_LIST_PIC + " text, "
                + KEY_COUNTRY_LIST_TITLE + " text, "
                + KEY_COUNTRY_LIST_URL + " text)";
        operating(db, sql);
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * @return 打开SQLiteDatabase 对象
     */
    public synchronized SQLiteDatabase openDb() {
        if (mDb == null) {
            mDb = getWritableDatabase();
        }

        mDBCount++;
        return mDb;
    }

    /**
     * 关闭数据库
     */
    public synchronized void closeDb() {
        if (mDb != null) {
            if (mDBCount == 0) {
                mDb.close();
                mDb = null;
            } else {
                mDBCount--;
            }
        }
    }


    private void operating(SQLiteDatabase db, String sql) {
        db.execSQL(sql);
    }
}
